<route lang="json5">
{
  style: {
    navigationBarTitleText: '发布动态'
  }
}
</route>

<script lang="ts" setup>
import type { MomentImage } from '@/store/moments'
import { ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { useMomentsStore } from '@/store/moments'

defineOptions({ name: 'PublishMoment' })

const momentsStore = useMomentsStore()
const { success: showSuccess, error: showError } = useToast()

const content = ref('')

// 改为与约会记录一致：使用字符串数组存本地路径
const photos = ref<string[]>([])
const publishing = ref(false)

// 压缩（与约会记录一致）
async function compressImageMp(path: string, quality = 70): Promise<string> {
  return await new Promise<string>((resolve, reject) => {
    uni.showLoading({ title: '压缩中...', mask: true })
    uni.compressImage({
      src: path,
      quality,
      success: (res) => {
        const out = (res as any).tempFilePath || path
        resolve(out)
      },
      fail: reject,
    })
  })
}

// 上传（与约会记录一致，使用 REST + anon key，入 images bucket）
async function uploadPhotos(localPaths: string[]): Promise<string[]> {
  try {
    uni.showLoading({ title: '上传中...', mask: true })
    const total = localPaths.length
    let finished = 0

    const uploadPromises = localPaths.map(async (photoPath) => {
      const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
      const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
      if (!supabaseUrl || !supabaseAnonKey) {
        throw new Error('环境变量缺失：VITE_SUPABASE_URL 或 VITE_SUPABASE_ANON_KEY')
      }

      const compressedPath = await compressImageMp(photoPath, 70)
      const ext = compressedPath.substring(compressedPath.lastIndexOf('.')) || photoPath.substring(photoPath.lastIndexOf('.'))
      const rand = Math.random().toString(36).slice(2, 8)
      const name = `moment-${Date.now()}-${rand}${ext}`

      const uploadUrl = `${supabaseUrl}/storage/v1/object/moments/${encodeURIComponent(name)}`
      await new Promise<void>((resolve, reject) => {
        const task = uni.uploadFile({
          url: uploadUrl,
          filePath: compressedPath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${supabaseAnonKey}`,
            'Cache-Control': '3600',
            'x-upsert': 'false',
          },
          success: (res) => {
            if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
              finished += 1
              uni.showLoading({ title: `上传中 ${finished}/${total}`, mask: true })
              resolve()
            }
            else {
              let detail = ''
              try {
                detail = res.data ? JSON.stringify(JSON.parse(res.data)) : ''
              }
              catch (e) {
                detail = res.data || ''
              }
              reject(new Error(`上传失败: ${res.statusCode} ${detail}`))
            }
          },
          fail: reject,
        })
        task.onProgressUpdate?.((p) => {
          uni.showLoading({ title: `上传中 ${p.progress}%`, mask: true })
        })
      })
      return `${supabaseUrl}/storage/v1/object/public/moments/${encodeURIComponent(name)}`
    })

    return await Promise.all(uploadPromises)
  }
  finally {
    uni.hideLoading()
  }
}

// 选择图片（与约会记录一致）
async function handleChooseImage() {
  const current = photos.value.length
  if (current >= 9) {
    showError('最多只能上传9张图片')
    return
  }
  try {
    const res: any = await uni.chooseMedia({
      count: 9 - current,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
    })
    const paths = (res?.tempFiles || []).map((f: any) => f.tempFilePath)
    photos.value.push(...paths)
  }
  catch {}
}

function handleRemoveImage(index: number) {
  photos.value.splice(index, 1)
}

function getPhotoUrl(p: string) {
  return p
}

function handlePreviewImage(list: string[], current: string) {
  uni.previewImage({ urls: list, current })
}

async function publishMoment() {
  if (!content.value.trim() && photos.value.length === 0) {
    showError('请输入文字内容或选择图片')
    return
  }
  if (publishing.value)
    return

  try {
    publishing.value = true

    // 与约会记录一致：统一上传
    let uploaded: string[] = []
    try {
      uploaded = await uploadPhotos(photos.value)
    }
    catch (e) {
      console.error('uploadPhotos error:', e)
      uni.showToast({ title: '图片上传失败，请检查网络与域名配置', icon: 'none' })
      throw e
    }

    const images: MomentImage[] = uploaded.map(u => ({
      url: u,
      name: '',
      size: 0,
    }))

    const role = uni.getStorageSync('whoAmI') as 'user1' | 'user2' | ''
    if (!role) {
      uni.showToast({ title: '请先选择身份', icon: 'none' })
      setTimeout(() => uni.navigateTo({ url: '/pages/whoami/index' }), 300)
      return
    }
    await momentsStore.createMoment(content.value.trim(), images)
    showSuccess('发布成功！')
    setTimeout(() => uni.navigateBack(), 500)
  }
  catch (err) {
    console.error('publishMoment error:', err)
    showError('发布失败，请重试')
  }
  finally {
    publishing.value = false
    uni.hideLoading()
  }
}

function goBack() {
  uni.navigateBack()
}
</script>

<template>
  <view class="publish-container">
    <!-- 内容输入区域 -->
    <view class="content-section">
      <wd-textarea
        v-model="content"
        placeholder="分享新鲜事..."
        :maxlength="500"
        show-word-limit
        :auto-height="true"
        :min-height="120"
        custom-class="content-textarea"
      />
    </view>

    <!-- 图片上传区域（与约会记录一致） -->
    <view class="upload-section">
      <view class="section-title">
        添加图片
      </view>
      <view class="photo-uploader">
        <view class="photo-grid">
          <view
            v-for="(p, index) in photos"
            :key="index"
            class="photo-item"
          >
            <image
              :src="getPhotoUrl(p)"
              mode="aspectFill"
              class="preview-img"
              @click="handlePreviewImage(photos, p)"
            />
            <view class="remove-icon" @click="handleRemoveImage(index)">
              <wd-icon name="close-bold" color="#fff" />
            </view>
          </view>
          <view v-if="photos.length < 9" class="add-photo-btn" @click="handleChooseImage">
            <wd-icon name="add" size="36px" color="#ccc" />
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <wd-button type="default" size="large" @click="goBack">
        取消
      </wd-button>
      <wd-button type="primary" size="large" :loading="publishing" :disabled="publishing" @click="publishMoment">
        {{ publishing ? '发布中...' : '发布' }}
      </wd-button>
    </view>

    <wd-toast />
  </view>
</template>

<style lang="scss" scoped>
.publish-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  padding: 16px 16px 120px; /* 为底部按钮留出空间 */
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 25% 25%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
    z-index: 0;
  }
}

.content-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  position: relative;
  z-index: 1;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.1);

  :deep(.content-textarea) {
    .wd-textarea__inner {
      border: none;
      background: transparent;
      font-size: 16px;
      line-height: 1.5;
    }

    .wd-textarea__count {
      color: #999;
      font-size: 12px;
    }
  }
}

.upload-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
  position: relative;
  z-index: 1;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.1);

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  /* 复用约会记录的样式 */
  .photo-uploader {
    margin-top: 8px;
  }
  .photo-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
  }
  .photo-item {
    position: relative;
    width: 100%;
    padding-top: 100%;
    border-radius: 8px;
    overflow: hidden;
    background: #f7f7f7;
  }
  .preview-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .remove-icon {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.35);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .add-photo-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100px;
    border-radius: 8px;
    border: 1px dashed #ddd;
    background: #fafafa;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  padding: 16px 16px 32px;
  position: fixed;
  bottom: 50px; /* 在 tabBar 上方 */
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 182, 193, 0.3);
  box-shadow: 0 -4px 12px rgba(255, 105, 180, 0.1);
  z-index: 1000;

  .wd-button {
    flex: 1;
  }
}

// 适配安全区域
@supports (bottom: env(safe-area-inset-bottom)) {
  .action-buttons {
    bottom: calc(50px + env(safe-area-inset-bottom));
    padding-bottom: calc(32px + env(safe-area-inset-bottom));
  }
}
</style>
